package com.hongyu.smart.village.ui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;

import androidx.loader.content.CursorLoader;

import com.hongyu.smart.village.R;
import com.hongyu.smart.village.event.Event;
import com.hongyu.smart.village.model.entity.BaseResponse;
import com.hongyu.smart.village.network.BaseObserver;
import com.hongyu.smart.village.network.FileUploadObserver;
import com.hongyu.smart.village.network.OkHttpManager;
import com.hongyu.smart.village.network.RetrofitClient;
import com.hongyu.smart.village.network.RetrofitHelper;
import com.hongyu.smart.village.network.RxUtil;
import com.hongyu.smart.village.network.UrlDefine;
import com.hongyu.smart.village.network.api.AppInfoApi;
import com.hongyu.smart.village.ui.base.BaseToolbarActivity;
import com.hongyu.smart.village.util.SPUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class MemberEditActivity extends BaseToolbarActivity {
    File file;
    FileUploadObserver observer;
    @BindView(R.id.iv_avator)
    ImageView ivAvator;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_ids)
    EditText etIds;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.et_nation)
    EditText etNation;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_addr)
    EditText etAddr;
    @BindView(R.id.sp_educat)
    Spinner spEducat;
    @BindView(R.id.rg_marriage)
    RadioGroup rgMarrige;
    @BindView(R.id.rg_political)
    RadioGroup rgPolitical;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;


    String img_src="";
    String filename="";
    int id=0;
    String  name="";//姓名
    String  ids="";//身份证号
    String  nation="";//民族
    String number="";//户号
    String  address="";//户籍地址
    String  ageStr="";//年龄
    String education="";//文化程度
    String political;//政治面貌
    String marriage="";//婚姻状况
    String addre="";//现居地址


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public String getToolBarTitle() {
        return "成员信息";
    }

    @Override
    protected void initActivityData() {
        rgMarrige.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

            }
        });
        rgPolitical.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

            }
        });
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

            }
        });
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,  R.array.edu_array, android.R.layout.simple_spinner_item);
        spEducat.setAdapter(adapter);
        spEducat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });



    }

    @Override
    protected void initContentView() {
        mBundle=getBundle();
        Log.e("MEMBERID",""+mBundle.getInt("MEMBERID"));
        number= SPUtil.getFamilyNumber();
        Log.e("FamilyNumber",number);
    }
    private File downLoadInfor(){
        OkHttpClient okHttpClient= OkHttpManager.getInstance();
        RequestBody body=new MultipartBody.Builder().addFormDataPart("filename",filename).build();
        FutureTask<File> task=new FutureTask<>(()->{
            ResponseBody responseBody=okHttpClient.newCall(
                    new Request.Builder().post(body).url(UrlDefine.BASE_URL + UrlDefine.FILE_DOWNLOAD).build()
            ).execute().body();
            if (responseBody!=null){
                if (getExternalFilesDir(null)!=null){
                    File file1=new File(getExternalFilesDir(null).toString()+"/0"+filename);
                    try (
                            InputStream inputStream = responseBody.byteStream();
                            FileOutputStream outputStream = new FileOutputStream(file1)
                    )
                    {
                        byte[] b = new byte[1024];
                        int n;
                        if((n = inputStream.read(b)) != -1)
                        {
                            outputStream.write(b,0,n);
                            while ((n = inputStream.read(b)) != -1)
                                outputStream.write(b, 0, n);
                            Bitmap bitmap=BitmapFactory.decodeFile(file1.getAbsolutePath());

                            return file1;
                        }
                        else
                        {
                            file1.delete();
                            return null;
                        }
                    }
                }
            }
            return null;
        });
        try
        {
            new Thread(task).start();

            return task.get();
        }
        catch (InterruptedException | ExecutionException e)
        {
            e.printStackTrace();
            return null;
        }


    }
    private void  uploadInfor(){

        RetrofitClient.getInstance().upLoadFile(UrlDefine.BASE_URL + UrlDefine.FILE_UPLOAD, file, new FileUploadObserver<ResponseBody>() {
            @Override
            public void onUpLoadSuccess(ResponseBody responseBody) {


            }

            @Override
            public void onUpLoadFail(Throwable e) {

            }

            @Override
            public void onProgress(int progress) {

            }
        });
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_member_edit;
    }

    @Override
    protected void onEventProcess(Event event) {

    }

    @OnClick({R.id.iv_avator,R.id.btn_save})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_avator:

                choosPictureFile();

                break;
            case R.id.btn_save:
                submitMemberInfo();
                break;

        }
    }

    private void submitMemberInfo() {
        name=etName.getText().toString();
        ids=etIds.getText().toString();
        nation=etNation.getText().toString();
        addre=etAddr.getText().toString();
        address=etAddress.getText().toString();
        ageStr=etAge.getText().toString();





        RetrofitHelper.create(AppInfoApi.class)
                .memberAdd(id,name,ids,nation,number, address, ageStr, education, political, marriage, addre)
                .compose(RxUtil.observervableToMain())
                .as(RxUtil.bindLifecycle( this))
                .subscribe(new BaseObserver<Object>(getLoadingDialog()){
                    @Override
                    public void onSuccess(BaseResponse<Object> response) {
                        if (response.getData()!=null) {



                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    Uri uri = data.getData();
                    img_src = uri.getPath();
                    ContentResolver cr = this.getContentResolver();
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                        String[] proj = {MediaStore.Images.Media.DATA};
                        ivAvator.setImageBitmap(bitmap);
                        CursorLoader loader = new CursorLoader(this, uri, proj, null, null, null);
                        Cursor cursor = loader.loadInBackground();
                        if (cursor != null) {
                            int colum_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            cursor.moveToFirst();
                            img_src = cursor.getString(colum_index);
                        }
                        cursor.close();
                    } catch (FileNotFoundException e) {
                        Log.e("cmd", e.getMessage(), e);
                    }
                    file=new File(img_src);
                    filename=file.getName();
                    downLoadInfor();
                    break;
            }
        }
//        super.onActivityResult(requestCode, resultCode, data);
    }
}